package com.coollang.smartbra.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.coollang.smartbra.MyAutoLayoutActivity;
import com.coollang.smartbra.R;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.bleutil.BleUtil;
import com.coollang.smartbra.bleutil.callback.BleCallbackImpl;
import com.coollang.smartbra.dfu.DfuService;
import com.coollang.smartbra.presenter.DeviceUpdateActivityPresenter;
import com.coollang.smartbra.utils.TranslucentSystemBarUtils;
import com.coollang.smartbra.views.OptionCircle;
import com.coollang.smartbra.views.RoundProgressBarWidthNumber;
import com.inuker.bluetooth.library.search.SearchResult;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import no.nordicsemi.android.dfu.DfuProgressListener;
import no.nordicsemi.android.dfu.DfuServiceInitiator;
import no.nordicsemi.android.dfu.DfuServiceListenerHelper;


/**
 * 固件升级页面
 */
public class DeviceUpdateActivity extends MyAutoLayoutActivity  {
    private static final String TAG = "DeviceUpdateActivity";
    @BindView(R.id.status_bar)
    View mStatusBar;
    @BindView(R.id.content)
    LinearLayout mContent;
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_update_info)
    TextView mTvUpDataInfo;
    @BindView(R.id.progress_bar)
    RoundProgressBarWidthNumber mProgressBar;
    @BindView(R.id.tv_update_state)
    TextView mTvUpdateState;
    @BindView(R.id.button)
    Button mButton;
    @BindView(R.id.cicleview)
    OptionCircle mOptionCircle;
    @BindView(R.id.tv_update_succ_info)
    TextView mTvUpdateSuccInfo;

    private boolean isUpdateing = false;
    private byte[] date = new byte[6];
    private DeviceUpdateActivityPresenter mPresenter;

    private String mMac = "";

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        setContentView(R.layout.activity_device_update);
        ButterKnife.bind(this);
        TranslucentSystemBarUtils.showChenJinZhuangTaiLan(mStatusBar, this, mContent);

        // 初始化View
        initViews();
    }

    private void initViews() {
        mTvTitle.setText("固件升级");
        mTvTitle.setTextColor(getResources().getColor(R.color.black_80));

        String text = "升级过程中，设备指示灯呈红蓝闪烁状态\n请勿断开升级连接";
        setTextFount(text);
        mProgressBar.setAngle();
        mOptionCircle.setPaintColor();

        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isUpdateing) {
                    finish();
                } else {
                    Toast.makeText(DeviceUpdateActivity.this, "固件正在升级中", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void setSuccTextFount(String text) {
        SpannableString msp = new SpannableString(text);
        // 设置字体大小
        msp.setSpan(new RelativeSizeSpan(1.28f), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置字体颜色

        mTvUpdateSuccInfo.setText(msp);
        mTvUpdateSuccInfo.setVisibility(View.VISIBLE);
        mButton.setText("完成");
    }

    private void setTextFount(String text) {
        SpannableString msp = new SpannableString(text);
        // 设置字体大小
        msp.setSpan(new ForegroundColorSpan(0xFFF79444), 12, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        msp.setSpan(new ForegroundColorSpan(0xFFF79444), 18, 23, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        mTvUpDataInfo.setText(msp);
    }

    @Override
    protected void initData() {
        super.initData();

        mMac = BleUtil.getInstance().getMac();

        BleUtil.getInstance().setUINO(false);
        mPresenter = new DeviceUpdateActivityPresenter(this);
        mPresenter.downLoadFile();
    }


    @Override
    protected void onResume() {
        super.onResume();
        BleUtil.getInstance().registerNotifyListener(mBleCallback);
        DfuServiceListenerHelper.registerProgressListener(this, mDfuProgressListener);
    }


    private BleCallbackImpl mBleCallback = new BleCallbackImpl() {
        @Override
        public void onBleConnected() {
            if (isUpdateing) {
                startUpDate();
            } else {
                BleUtil.getInstance().sendData((byte) 07);
                mOptionCircle.setCircleVisible(false);
                setSuccTextFount("连接成功\n序列号：" + MyApplication.getApplication().deviceName);
            }
        }

        @Override
        public void onBleDisconnected() {
            if (isUpdateing) {
                reConnection();
            }
        }

        @Override
        public void onScan(SearchResult result) {
            String address = result.getAddress();
            if (getDFUMac(mMac).equals(address)) {
                // 停止扫描
                BleUtil.getInstance().stopSearch();
                BleUtil.getInstance().connect(address);
            }
        }

        @Override
        public void onUpdateDataBackup(byte voc1, byte voc2, byte voc3, byte voc4, byte step1, byte step2) {
            date[0] = voc1;
            date[1] = voc2;
            date[2] = voc3;
            date[3] = voc4;
            date[4] = step1;
            date[5] = step2;

            isUpdateing = true;

            BleUtil.getInstance().sendData((byte) 5, (byte) 7);
        }

        @Override
        protected void onUpdateDataRecovery(byte sign) {
            if (sign == 1) {
                BleUtil.getInstance().sendData((byte) 8, (byte) 01, date[0], date[1], date[2], date[3], date[4], date[5]);
            }
        }

        @Override
        protected void onUpdateDataRecoverySign(byte sign) {
            if (sign == 1) {
                // 说明设备恢复数据成功
            }
        }
    };


    /**
     * 固件升级 重新连接
     */
    private void reConnection() {
        // 尝试重新连接 MAC地址+1
        //TODO: BleUtil.getInstance().connect(getDFUMac(mMac));
        BleUtil.getInstance().search();

    }

    @Override
    protected void onDestroy() {
        BleUtil.getInstance().setUINO(true);
        DfuServiceListenerHelper.unregisterProgressListener(this, mDfuProgressListener);
        BleUtil.getInstance().unRegisterNotifyListener();

        super.onDestroy();
    }


    /**
     * 开始固件升级
     */
    private void startUpDate() {
        String updateZip = Environment.getExternalStorageDirectory().toString() + "/smartbra/update/update.zip";
        new DfuServiceInitiator(getDFUMac(mMac))
                .setDisableNotification(true)
                .setZip(updateZip)
                .start((getBaseContext()), DfuService.class);
    }

    private DfuProgressListener mDfuProgressListener = new DfuProgressListener() {
        @Override
        public void onDeviceConnecting(String deviceAddress) {
        }

        @Override
        public void onDeviceConnected(String deviceAddress) {
        }

        @Override
        public void onDfuProcessStarting(String deviceAddress) {
        }

        @Override
        public void onDfuProcessStarted(String deviceAddress) {
        }

        @Override
        public void onEnablingDfuMode(String deviceAddress) {
        }

        @Override
        public void onProgressChanged(String deviceAddress, int percent, float speed, float avgSpeed, int currentPart, int partsTotal) {

            mProgressBar.setProgress(percent);
        }

        @Override
        public void onFirmwareValidating(String deviceAddress) {
        }

        @Override
        public void onDeviceDisconnecting(String deviceAddress) {
            isUpdateing = false;
        }

        @Override
        public void onDeviceDisconnected(String deviceAddress) {
            isUpdateing = false;
        }

        @Override
        public void onDfuCompleted(String deviceAddress) {
            isUpdateing = true;
            mProgressBar.setProgress(100);
            mTvUpdateState.setText("升级成功");
            mButton.setText("重新连接");
            String text = "升级成功后，设备指示灯呈蓝色闪烁状态\n现在已经是最新版本";
            setTextFount2(text);
        }

        @Override
        public void onDfuAborted(String deviceAddress) {
            isUpdateing = false;
        }

        @Override
        public void onError(String deviceAddress, int error, int errorType, String message) {
            isUpdateing = false;
        }
    };

    private void setTextFount2(String text) {
        SpannableString msp = new SpannableString(text);
        // 设置字体颜色
        msp.setSpan(new ForegroundColorSpan(0xFFF79444), 12, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTvUpDataInfo.setText(msp);

        mButton.setBackgroundResource(R.drawable.shape_btn_stroke);
        mButton.setTextColor(Color.parseColor("#F79444"));
    }


    @OnClick(R.id.button)
    public void onViewClicked() {
        String text = mButton.getText().toString();
        if ("重新连接".equals(text)) {
            reConnectionUI();
            BleUtil.getInstance().connect(mMac);
        } else if ("完成".equals(text)) {
            finish();
        }
    }

    private void reConnectionUI() {
        mButton.setText("正在重连...");
        mProgressBar.setVisibility(View.GONE);
        mOptionCircle.setVisibility(View.VISIBLE);
        mOptionCircle.startCountdown();
    }

    @Override
    public void onBackPressed() {

        if (isUpdateing) {
            super.onBackPressed();
        } else {
            Toast.makeText(this, "固件正在升级中", Toast.LENGTH_SHORT).show();
        }
    }


    public static String getDFUMac(String mac) {
        String[] split = mac.split(":");
        String a = split[split.length - 1];
        int b = Integer.parseInt(a, 16) + 1;

        String c = Integer.toHexString(b);


        if (b == 256) {
            c = "00";
        }

        split[split.length - 1] = c.toUpperCase();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < split.length; i++) {
            sb.append(split[i]);
            if (i != split.length - 1) {

                sb.append(":");
            }
        }

        return sb.toString();
    }

    public void downloadSucceed(String updateZip) {
        BleUtil.getInstance().sendData((byte) 6);
    }

    // 下载失败
    public void downloadError() {
        Toast.makeText(this, "文件下载失败", Toast.LENGTH_SHORT).show();
    }
}
